﻿using System;
using System.Data;
using System.Text;
using System.Data.SqlClient;
using IPR_StudyMeetingMrgSys.DBUtility;//Please add references
namespace IPR_StudyMeetingMrgSys.DAL
{
	/// <summary>
	/// 数据访问类:TrainPlanSendStep
	/// </summary>
	public partial class TrainPlanSendStep
	{
		public TrainPlanSendStep()
		{}
		#region  BasicMethod



		/// <summary>
		/// 增加一条数据
		/// </summary>
		public long Add(IPR_StudyMeetingMrgSys.Model.TrainPlanSendStep model,out string errorMsg)
		{
			StringBuilder strSql=new StringBuilder();

            errorMsg = String.Empty;
            StringBuilder strSql_select = new StringBuilder();

            #region 计划是否是 审核并发布
            strSql_select = new StringBuilder();
            strSql_select.Append("select  top 1 TPIsRelease,IsCheck from TrainPlan ");
            strSql_select.Append(" where TPID='" + model.TPID + "' ");
            DataSet ds = DbHelperSQL.Query(strSql_select.ToString());
            if (ds.Tables[0].Rows.Count > 0)
            {
                    var item = ds.Tables[0].Rows[0];
                    if (item["TPIsRelease"] != null && item["TPIsRelease"].ToString() != ""&& item["IsCheck"] != null && item["IsCheck"].ToString() != "")
                    {
                        if (int.Parse(item["IsCheck"].ToString()) == 0)
                        {
                            errorMsg = "该计划未审核,不能执行下发操作";return 0;
                        }
                        //if (int.Parse(item["TPIsRelease"].ToString()) == 0)
                        //{
                        //    errorMsg = "该计划未发布,不能执行下发操作"; return 0;
                        //}
                    }
            }
            else
            {
                errorMsg = "没有该计划的记录,请刷新(有可能已被删除)"; return 0;
            }
            #endregion

            #region 下发记录校验
            strSql_select = new StringBuilder();
            strSql_select.Append("select  top 1 TPID from TrainPlanSendStep ");
            strSql_select.Append(" where TPID=@TPID AND DeptID=@DeptID");
            SqlParameter[] parameters_select = {
                    new SqlParameter("@TPID", SqlDbType.BigInt),
                     new SqlParameter("@DeptID", SqlDbType.Int)
            };
            parameters_select[0].Value = model.TPID;
            parameters_select[1].Value = model.DeptID;
            DataSet ds1 = DbHelperSQL.Query(strSql_select.ToString(), parameters_select);
            if (ds1.Tables[0].Rows.Count > 0)
            {
                var item = ds1.Tables[0].Rows[0];
                if (item["TPID"] != null && item["TPID"].ToString() != "")
                {
                    if (int.Parse(item["TPID"].ToString()) > 0)
                    {
                        errorMsg = "已有下发记录"; return 0;
                    }
                }
            }
            #endregion

            strSql.Append("insert into TrainPlanSendStep(");
			strSql.Append("TPID,SendID,SendStep,DeptID,DeptLevel,SendState,SendDateTime,SendUserID,CreateUserID,CreateUserName,CreateDateTime)");
			strSql.Append(" values (");
			strSql.Append("@TPID,@SendID,@SendStep,@DeptID,@DeptLevel,@SendState,@SendDateTime,@SendUserID,@CreateUserID,@CreateUserName,@CreateDateTime)");
			strSql.Append(";select @@IDENTITY");
			SqlParameter[] parameters = {
					new SqlParameter("@TPID", SqlDbType.BigInt,8),
					new SqlParameter("@SendID", SqlDbType.BigInt,8),
					new SqlParameter("@SendStep", SqlDbType.NVarChar,30),
					new SqlParameter("@DeptID", SqlDbType.Int,4),
					new SqlParameter("@DeptLevel", SqlDbType.Int,4),
					new SqlParameter("@SendState", SqlDbType.Int,4),
					new SqlParameter("@SendDateTime", SqlDbType.DateTime),
					new SqlParameter("@SendUserID", SqlDbType.NVarChar,20),
					new SqlParameter("@CreateUserID", SqlDbType.NVarChar,20),
					new SqlParameter("@CreateUserName", SqlDbType.NVarChar,20),
					new SqlParameter("@CreateDateTime", SqlDbType.DateTime)};
			parameters[0].Value = model.TPID;
			parameters[1].Value = model.SendID;
			parameters[2].Value = model.SendStep;
			parameters[3].Value = model.DeptID;
			parameters[4].Value = model.DeptLevel;
			parameters[5].Value = model.SendState;
			parameters[6].Value = model.SendDateTime;
			parameters[7].Value = model.SendUserID;
			parameters[8].Value = model.CreateUserID;
			parameters[9].Value = model.CreateUserName;
			parameters[10].Value = model.CreateDateTime;

			object obj = DbHelperSQL.GetSingle(strSql.ToString(),parameters);
			if (obj == null)
			{
				return 0;
			}
			else
			{
				return Convert.ToInt64(obj);
			}
		}
		/// <summary>
		/// 更新一条数据
		/// </summary>
		public bool Update(IPR_StudyMeetingMrgSys.Model.TrainPlanSendStep model,out string ErrorMsg)
		{
            ErrorMsg = string.Empty;
            StringBuilder strSql=new StringBuilder();

            int rows = 0;
            if (string.IsNullOrEmpty(ErrorMsg)) {
                strSql.Append("update TrainPlanSendStep set ");
                strSql.Append("SendState=@SendState,");
                strSql.Append("SendDateTime=@SendDateTime,");
                strSql.Append("SendUserID=@SendUserID");
                strSql.Append(" where SendID=@SendID");
                SqlParameter[] parameters = {
					new SqlParameter("@SendState", SqlDbType.Int,4),
                    new SqlParameter("@SendDateTime", SqlDbType.DateTime),
                    new SqlParameter("@SendUserID", SqlDbType.NVarChar,20),
					new SqlParameter("@SendID", SqlDbType.BigInt,8)
            };
                parameters[0].Value = model.SendState;
                parameters[1].Value = model.SendDateTime;
                parameters[2].Value = model.SendUserID;
                parameters[3].Value = model.SendID;
                rows = DbHelperSQL.ExecuteSql(strSql.ToString(), parameters);
                
            }
            if (rows > 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

		/// <summary>
		/// 删除一条数据
		/// </summary>
		public bool Delete(long AutoID)
		{
			
			StringBuilder strSql=new StringBuilder();
			strSql.Append("delete from TrainPlanSendStep ");
			strSql.Append(" where AutoID=@AutoID");
			SqlParameter[] parameters = {
					new SqlParameter("@AutoID", SqlDbType.BigInt)
			};
			parameters[0].Value = AutoID;

			int rows=DbHelperSQL.ExecuteSql(strSql.ToString(),parameters);
			if (rows > 0)
			{
				return true;
			}
			else
			{
				return false;
			}
		}
		/// <summary>
		/// 批量删除数据
		/// </summary>
		public bool DeleteList(string AutoIDlist )
		{
			StringBuilder strSql=new StringBuilder();
			strSql.Append("delete from TrainPlanSendStep ");
			strSql.Append(" where AutoID in ("+AutoIDlist + ")  ");
			int rows=DbHelperSQL.ExecuteSql(strSql.ToString());
			if (rows > 0)
			{
				return true;
			}
			else
			{
				return false;
			}
		}


		/// <summary>
		/// 得到一个对象实体
		/// </summary>
		public IPR_StudyMeetingMrgSys.Model.TrainPlanSendStep GetModel(long AutoID)
		{
			
			StringBuilder strSql=new StringBuilder();
			strSql.Append("select  top 1 AutoID,TPID,SendID,SendStep,DeptID,DeptLevel,SendState,SendDateTime,SendUserID,CreateUserID,CreateUserName,CreateDateTime from TrainPlanSendStep ");
			strSql.Append(" where AutoID=@AutoID");
			SqlParameter[] parameters = {
					new SqlParameter("@AutoID", SqlDbType.BigInt)
			};
			parameters[0].Value = AutoID;

			IPR_StudyMeetingMrgSys.Model.TrainPlanSendStep model=new IPR_StudyMeetingMrgSys.Model.TrainPlanSendStep();
			DataSet ds=DbHelperSQL.Query(strSql.ToString(),parameters);
			if(ds.Tables[0].Rows.Count>0)
			{
				return DataRowToModel(ds.Tables[0].Rows[0]);
			}
			else
			{
				return null;
			}
		}


		/// <summary>
		/// 得到一个对象实体
		/// </summary>
		public IPR_StudyMeetingMrgSys.Model.TrainPlanSendStep DataRowToModel(DataRow row)
		{
			IPR_StudyMeetingMrgSys.Model.TrainPlanSendStep model=new IPR_StudyMeetingMrgSys.Model.TrainPlanSendStep();
			if (row != null)
			{
				if(row["AutoID"]!=null && row["AutoID"].ToString()!="")
				{
					model.AutoID=long.Parse(row["AutoID"].ToString());
				}
				if(row["TPID"]!=null && row["TPID"].ToString()!="")
				{
					model.TPID=long.Parse(row["TPID"].ToString());
				}
				if(row["SendID"]!=null && row["SendID"].ToString()!="")
				{
					model.SendID=long.Parse(row["SendID"].ToString());
				}
				if(row["SendStep"]!=null)
				{
					model.SendStep=row["SendStep"].ToString();
				}
				if(row["DeptID"]!=null && row["DeptID"].ToString()!="")
				{
					model.DeptID=int.Parse(row["DeptID"].ToString());
				}
				if(row["DeptLevel"]!=null && row["DeptLevel"].ToString()!="")
				{
					model.DeptLevel=int.Parse(row["DeptLevel"].ToString());
				}
				if(row["SendState"]!=null && row["SendState"].ToString()!="")
				{
					model.SendState=int.Parse(row["SendState"].ToString());
				}
				if(row["SendDateTime"]!=null && row["SendDateTime"].ToString()!="")
				{
					model.SendDateTime=DateTime.Parse(row["SendDateTime"].ToString());
				}
				if(row["SendUserID"]!=null)
				{
					model.SendUserID=row["SendUserID"].ToString();
				}
				if(row["CreateUserID"]!=null)
				{
					model.CreateUserID=row["CreateUserID"].ToString();
				}
				if(row["CreateUserName"]!=null)
				{
					model.CreateUserName=row["CreateUserName"].ToString();
				}
				if(row["CreateDateTime"]!=null && row["CreateDateTime"].ToString()!="")
				{
					model.CreateDateTime=DateTime.Parse(row["CreateDateTime"].ToString());
				}
			}
			return model;
		}

		/// <summary>
		/// 获得数据列表
		/// </summary>
		public DataSet GetList(string strWhere)
		{
			StringBuilder strSql=new StringBuilder();
			strSql.Append("select AutoID,TPID,SendID,SendStep,DeptID,DeptLevel,SendState,SendDateTime,SendUserID,CreateUserID,CreateUserName,CreateDateTime ");
			strSql.Append(" FROM TrainPlanSendStep ");
			if(strWhere.Trim()!="")
			{
				strSql.Append(" where "+strWhere);
			}
			return DbHelperSQL.Query(strSql.ToString());
		}

		/// <summary>
		/// 获得前几行数据
		/// </summary>
		public DataSet GetList(int Top,string strWhere,string filedOrder)
		{
			StringBuilder strSql=new StringBuilder();
			strSql.Append("select ");
			if(Top>0)
			{
				strSql.Append(" top "+Top.ToString());
			}
			strSql.Append(" AutoID,TPID,SendID,SendStep,DeptID,DeptLevel,SendState,SendDateTime,SendUserID,CreateUserID,CreateUserName,CreateDateTime ");
			strSql.Append(" FROM TrainPlanSendStep ");
			if(strWhere.Trim()!="")
			{
				strSql.Append(" where "+strWhere);
			}
			strSql.Append(" order by " + filedOrder);
			return DbHelperSQL.Query(strSql.ToString());
		}

		/// <summary>
		/// 获取记录总数
		/// </summary>
		public int GetRecordCount(string strWhere)
		{
			StringBuilder strSql=new StringBuilder();
			strSql.Append("select count(1) FROM TrainPlanSendStep ");
			if(strWhere.Trim()!="")
			{
				strSql.Append(" where "+strWhere);
			}
			object obj = DbHelperSQL.GetSingle(strSql.ToString());
			if (obj == null)
			{
				return 0;
			}
			else
			{
				return Convert.ToInt32(obj);
			}
		}
		/// <summary>
		/// 分页获取数据列表
		/// </summary>
		public DataSet GetListByPage(string strWhere, string orderby, int startIndex, int endIndex)
		{
			StringBuilder strSql=new StringBuilder();
			strSql.Append("SELECT * FROM ( ");
			strSql.Append(" SELECT ROW_NUMBER() OVER (");
			if (!string.IsNullOrEmpty(orderby.Trim()))
			{
				strSql.Append("order by T." + orderby );
			}
			else
			{
				strSql.Append("order by T.AutoID desc");
			}
			strSql.Append(")AS Row, T.*  from TrainPlanSendStep T ");
			if (!string.IsNullOrEmpty(strWhere.Trim()))
			{
				strSql.Append(" WHERE " + strWhere);
			}
			strSql.Append(" ) TT");
			strSql.AppendFormat(" WHERE TT.Row between {0} and {1}", startIndex, endIndex);
			return DbHelperSQL.Query(strSql.ToString());
		}

        /// <summary>
        /// 读取视图
        /// </summary>
        /// <param name="strWhere"></param>
        /// <param name="orderby"></param>
        /// <param name="startIndex"></param>
        /// <param name="endIndex"></param>
        /// <returns></returns>
        public DataSet GetListByPage2(string strWhere, string orderby, int startIndex, int endIndex)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("SELECT * FROM ( ");
            strSql.Append(" SELECT ROW_NUMBER() OVER (");
            if (!string.IsNullOrEmpty(orderby.Trim()))
            {
                strSql.Append("order by T." + orderby);
            }
            else
            {
                strSql.Append("order by T.AutoID desc");
            }
            strSql.Append(")AS Row, T.*  from TrainPlanSendStep_view T ");
            if (!string.IsNullOrEmpty(strWhere.Trim()))
            {
                strSql.Append(" WHERE " + strWhere);
            }
            strSql.Append(" ) TT");
            strSql.AppendFormat(" WHERE TT.Row between {0} and {1}", startIndex, endIndex);
            return DbHelperSQL.Query(strSql.ToString());
        }

        /*
		/// <summary>
		/// 分页获取数据列表
		/// </summary>
		public DataSet GetList(int PageSize,int PageIndex,string strWhere)
		{
			SqlParameter[] parameters = {
					new SqlParameter("@tblName", SqlDbType.VarChar, 255),
					new SqlParameter("@fldName", SqlDbType.VarChar, 255),
					new SqlParameter("@PageSize", SqlDbType.Int),
					new SqlParameter("@PageIndex", SqlDbType.Int),
					new SqlParameter("@IsReCount", SqlDbType.Bit),
					new SqlParameter("@OrderType", SqlDbType.Bit),
					new SqlParameter("@strWhere", SqlDbType.VarChar,1000),
					};
			parameters[0].Value = "TrainPlanSendStep";
			parameters[1].Value = "AutoID";
			parameters[2].Value = PageSize;
			parameters[3].Value = PageIndex;
			parameters[4].Value = 0;
			parameters[5].Value = 0;
			parameters[6].Value = strWhere;	
			return DbHelperSQL.RunProcedure("UP_GetRecordByPage",parameters,"ds");
		}*/

        #endregion  BasicMethod
        #region  ExtensionMethod
        public int DeleteListByTPID(string TPIDlist)
        {
            StringBuilder strSql = new StringBuilder();

            var listid = "0";
            StringBuilder strSql_select = new StringBuilder();
            strSql_select.Append("select  top 1 TPID from TrainPlanSendStep ");
            strSql_select.Append(" where TPID in (" + TPIDlist + ") and SendState='0' ");
            DataSet ds = DbHelperSQL.Query(strSql_select.ToString());
            if (ds.Tables[0].Rows.Count > 0)
            {
                //var item = ds.Tables[0].Rows[0];
                for(int i=0;i<ds.Tables[0].Rows.Count;i++)
                {
                    var item = ds.Tables[0].Rows[i];
                    if (item["TPID"] != null && item["TPID"].ToString() != "")
                    {
                        if (int.Parse(item["TPID"].ToString()) > 0)
                        {
                            listid += ","+ item["TPID"].ToString() + "";
                        }
                    }
                }
            }
            strSql.Append("delete from TrainPlanSendStep ");
            strSql.Append(" where TPID in (" + listid + ")  ");
             strSql.Append("delete from TrainPlanSendDept ");
            strSql.Append(" where TPID in (" + listid + ")  ");
            int rows = DbHelperSQL.ExecuteSql(strSql.ToString());
            return rows;
        }
        #endregion  ExtensionMethod
    }
}

